﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using Xms.CRM;
using Xms.CRM.Domain;
using Xms.Infrastructure.Utility;
using Xms.Web.Framework.Context;
using Xms.Web.Framework.Controller;
using Xms.Web.Models;

namespace Xms.Web.Controllers
{
    /// <summary>
    /// 配置管理控制器
    /// </summary>
    public class CampusHolidayController : AuthorizedControllerBase
    {
        private readonly ICampusHolidayService _campusHolidayService;

        public CampusHolidayController(IWebAppContext appContext
            , ICampusHolidayService campusHolidayService)
            : base(appContext)
        {
            _campusHolidayService = campusHolidayService;
        }

        #region 节假日

        [HttpGet]
        [Description("编辑节假日")]
        public IActionResult HolidaySet()
        {
            return View();
        }

        [HttpGet]
        [Description("获取节假日")]
        public IActionResult Query(int year)
        {
            var firstDate = new DateTime(year, 1, 1);
            var lastDate = new DateTime(year, 12, 31);
            return Json(_campusHolidayService.Query(t => t.Where(p => p.HolidayDate >= firstDate && p.HolidayDate <= lastDate)));
        }

        [HttpPost]
        [Description("保存节假日")]
        public IActionResult Save([FromBody]HolidaySetListModel model)
        {
            if (model.Holidays.Count > 0)
            {
                var first = model.Holidays.FirstOrDefault();
                var date = DateTime.Parse(first.HolidayDate);
                var firstDate = new DateTime(date.Year, 1, 1);
                var lastDate = new DateTime(date.Year, 12, 31);

                //先删除今年的数据
                var oldData = _campusHolidayService.Query(t => t.Where(p => p.HolidayDate >= firstDate && p.HolidayDate <= lastDate));
                _campusHolidayService.DeleteById(oldData.Select(t => t.Id).ToList());

                //再新增
                var newData = new List<CampusHoliday>();
                model.Holidays.ForEach(t =>
                {
                    newData.Add(new CampusHoliday
                    {
                        Id = Guid.NewGuid(),
                        Name = t.Name,
                        HolidayDate = DateTime.Parse(t.HolidayDate),
                        Remark = "",
                        CreatedBy = CurrentUser.SystemUserId,
                        CreatedOn = DateTime.Now
                    });
                });
                _campusHolidayService.CreateMany(newData);
            }
            return SaveSuccess();
        }

        #endregion
    }
}